package com.uduew.sjd.ui.form

import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.view.View
import android.view.View.GONE
import android.view.View.OnClickListener
import android.view.View.VISIBLE
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bumptech.glide.Glide
import com.uduew.sjd.config.CameraDefine.CameraType
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.AppointFormApi
import com.uduew.sjd.api.CertificateApi
import com.uduew.sjd.api.FormListApi
import com.uduew.sjd.api.GetAddressApi
import com.uduew.sjd.api.UploadFileApi
import com.uduew.sjd.api.UploadUserInfoApi
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.bean.MotheryBean
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.config.Const
import com.uduew.sjd.databinding.ActivityFormBinding
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataRepository
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.AppointFormRequester
import com.uduew.sjd.request.CertificateRequester
import com.uduew.sjd.request.FormRequester
import com.uduew.sjd.request.SubmitFormRequester
import com.uduew.sjd.request.UploadFileRequester
import com.uduew.sjd.request.UploadUserInfoRequester
import com.uduew.sjd.ui.base.BaseActivity
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.FormUtils
import com.uduew.sjd.utils.MainHandler
import com.uduew.sjd.utils.SpannableUtils
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.uduew.sjd.view.xpop.IdCardXpop
import com.uduew.sjd.view.xpop.UserInfoXpop
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.raedev.forms.FormGroup
import com.raedev.forms.FormGroupAdapter
import com.raedev.forms.dict.FormDataProvider
import com.raedev.forms.dict.FormSelectItem
import com.raedev.forms.dict.SimpleDataProvider
import com.raedev.forms.filter.FormValueFilter
import com.raedev.forms.items.ButtonFormItem.OnAddListener
import com.raedev.forms.items.EditTextFormItem.OnContactSelectedListener
import com.raedev.forms.items.EditTextFormItem.OnTipListener
import com.raedev.forms.items.FormItem
import com.raedev.forms.items.IdCardFormItem.OnIdAddListener
import com.raedev.forms.items.IdCardFormItem.OnIdCardListener
import com.raedev.forms.items.SelectFormItem
import com.raedev.forms.items.SelectFormItem.OnSelectedListener
import com.raedev.forms.render.DataBindingFormRender
import com.raedev.forms.view.FormEditText
import com.raedev.forms.view.FormLayoutManager
import com.uduew.sjd.utils.AndroidBug5497Workaround2
import com.uduew.utils.BarUtils
import com.uduew.utils.GsonUtils
import java.io.File
import kotlin.collections.get
import kotlin.collections.iterator

class FormActivity : BaseActivity() {

    lateinit var mState: FormStates
    private val mAdapter = FormGroupAdapter()
    lateinit var render: DataBindingFormRender
    private val formGroup: FormGroup
        get() = mAdapter.formGroup

    private lateinit var mFormRequester: FormRequester
    private lateinit var mAppointFormRequester: AppointFormRequester
    private lateinit var mSubmitFormRequester: SubmitFormRequester
    private lateinit var mAddressProvider: FormDataProvider
    private lateinit var mUploadFileRequester: UploadFileRequester
    private lateinit var mCertificateRequester: CertificateRequester
    private lateinit var mUploadUserInfoRequester: UploadUserInfoRequester
    private lateinit var mMessenger: PageMessenger

    var currentControl = ""
    var mTerephthalate = ""
    private lateinit var currentCameraType: CameraType
    private lateinit var currentPhotoFile: File
    private lateinit var currentPhotoUrl: String

    override fun initViewModel() {
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)

        mState = getActivityScopeViewModel(FormStates::class.java)
        mFormRequester = getActivityScopeViewModel(FormRequester::class.java)
        mAppointFormRequester = getActivityScopeViewModel(AppointFormRequester::class.java)
        mSubmitFormRequester =
            getActivityScopeViewModel(SubmitFormRequester::class.java)
        mUploadFileRequester =
            getActivityScopeViewModel(UploadFileRequester::class.java)
        mUploadUserInfoRequester = getActivityScopeViewModel(UploadUserInfoRequester::class.java)
        mCertificateRequester = getActivityScopeViewModel(CertificateRequester::class.java)
    }

    override fun onDestroy() {
        super.onDestroy()
//        CameraOptions.getOptionsInstance().clearListeners()
    }


    private val mNameHasMap = hashMapOf<String, EditText>()

    private val contactLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK && result.data != null) {
            result.data?.data?.let { contactUri ->
                val contactInfo = FormUtils.getContactInfo(this, contactUri)
                if (contactInfo.phone.isNotEmpty()) {
                    mState.editTextPhone?.setText(contactInfo.phone)
                    var editTextName = mNameHasMap[mState.editTextPhone?.tag]
                    contactInfo.name.toString().let {
                        editTextName?.setText(it)
                    }

                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.no_valid_number_was_obtained), Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    private fun setSpannable(str1: String, str2: String, it: AppCompatTextView) {
        val text = str1 + str2
        val spannableString = SpannableUtils.setTextColor(
            text,
            text.indexOf(str2),
            text.length,
            ContextCompat.getColor(this, R.color.orange_700)
        )
        it.text = spannableString
    }


    private fun setIdFrontCardData(str1: String, str2: String, uploadRes: Boolean) {
        mState.idCardFrontImageView.let {
            if (it != null) {
                if (mState.landmass.get() == null || mState.landmass.get() == "") {
                    Glide.with(this).load(R.drawable.id_card_front).into(it)
                } else {
                    Glide.with(this).load(currentPhotoFile).into(it)
                }
            }
        }
        mState.idCardFrontStateView.let {
            if (it != null) {
                it.visibility = VISIBLE
                if (uploadRes) {
                    it.setImageResource(R.mipmap.upload_success_icon)
                } else {
                    it.setImageResource(R.mipmap.upload_fail_icon)
                }
            }
        }
        mState.idCardFrontTipView.let {
            if (it != null) {
                setSpannable(str1, str2, it)
            }
        }
    }

    private fun setIdBackCardData(str1: String, str2: String, uploadRes: Boolean) {
        mState.idCardBackImageView.let {
            if (it != null) {
                if (mState.dimerize.get() == null || mState.dimerize.get() == "") {
                    Glide.with(this).load(R.drawable.id_card_of_back).into(it)
                } else {
                    Glide.with(this).load(currentPhotoFile).into(it)
                }

            }
        }
        mState.idCardBackStateView.let {
            if (it != null) {
                it.visibility = VISIBLE
                if (uploadRes) {
                    it.setImageResource(R.mipmap.upload_success_icon)
                } else {
                    it.setImageResource(R.mipmap.upload_fail_icon)
                }
            }
        }
        mState.idCardBackTipView.let {
            if (it != null) {
                setSpannable(str1, str2, it)
            }
        }
    }

    var isApplyingInsets = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val content = this.findViewById<FrameLayout>(android.R.id.content)
        ViewCompat.setOnApplyWindowInsetsListener(content) { v, insets ->
            if (isApplyingInsets) return@setOnApplyWindowInsetsListener insets
            isApplyingInsets = true
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            AndroidBug5497Workaround2.assistActivity(this, true, systemBars.bottom)
            insets
        }
        BarUtils.setNavBarLightMode(this, true)
        val formMap = GsonUtils.fromJson(
            AppConfig.mConfigs.form().get(),
            HashMap::class.java
        )

        (getBinding() as ActivityFormBinding).apply {
            recyclerView.adapter = mAdapter
            recyclerView.layoutManager = FormLayoutManager(this@FormActivity, formGroup)
            this@FormActivity.render =
                DataBindingFormRender(this@FormActivity, mAdapter, supportFragmentManager)
            render.render()
        }
        mMessenger.output(this) { messages ->
            if (messages.eventId == Messages.EVENT_CERTIFICATION_SUCCESS) {
                finish()
            }
        }
        mUploadUserInfoRequester.result.observe(this) { dataResult: DataResult<HttpBean<Any>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            Intent(this, FormActivity::class.java).apply {
                startActivity(this)
                finish()
            }
        }

        mSubmitFormRequester.result.observe(this) { dataResult: DataResult<HttpBean<Any>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            AppConfig.mConfigs.form().set("")
            mState.isNext = true
            WaitDialog.show(getString(R.string.loading))
            mFormRequester.request(this, Const.THEOLOGIST)
        }

        //获取一个未完成表单
        mFormRequester.result.observe(this) { dataResult: DataResult<HttpBean<FormListApi.FormListBean>> ->
            if (!dataResult.responseStatus.isSuccess) {
                WaitDialog.dismiss()
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            if (dataResult.result.data?.mothery?.size == 0) {
                WaitDialog.dismiss()
//                mMessenger.input(Messages(Messages.EVENT_CERTIFICATION_SUCCESS))
                finish()
            } else if (mState.isNext) {
                Intent(this, FormActivity::class.java).apply {
                    startActivity(this)
                    finish()
                }
            }
            AppConfig.unfinishedFormCount = dataResult.result.data?.mothery?.size ?: 0
            dataResult.result.data?.mothery?.let {
                mState.formCount.set(5 - it.size)
            }

            dataResult.result.data?.mothery?.firstOrNull()?.control?.let { control ->
                currentControl = control
                mAppointFormRequester.request(
                    this,
                    control,
                    Const.THEOLOGIST
                )
            }
        }
        mCertificateRequester.result.observe(this) { dataResult: DataResult<HttpBean<CertificateApi.ResCertificateBean>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                if (currentCameraType == CameraType.Front) {
                    mState.uploadFrontRes.set(false)
                    mState.uploadSuccessFront.set(true)
                    mState.landmass.set("")
                    setIdFrontCardData(
                        getString(R.string.upload_failed),
                        getString(R.string.click_to_re_upload), false
                    )
                } else if (currentCameraType == CameraType.Back) {
                    mState.uploadBackRes.set(false)
                    mState.uploadSuccessBack.set(true)
                    mState.dimerize.set("")
                    setIdBackCardData(
                        getString(R.string.upload_failed),
                        getString(R.string.click_to_re_upload),
                        false
                    )
                }
                return@observe
            }
            dataResult.result.data.let {
                if (it != null) {
                    if (currentCameraType == CameraType.Front) {
                        mState.uploadSuccessFront.set(true)
                        addOcrItem(it, false)
                        mState.landmass.set(currentPhotoUrl)
                        mState.uploadFrontRes.set(true)
                        setIdFrontCardData(
                            getString(R.string.upload),
                            getString(R.string.success), true
                        )
                    } else if (currentCameraType == CameraType.Back) {
                        mState.uploadSuccessBack.set(true)
                        mState.uploadBackRes.set(true)
                        mState.dimerize.set(currentPhotoUrl)
                        setIdBackCardData(
                            getString(R.string.upload),
                            getString(R.string.success),
                            true
                        )
                        if (it.clypeiform != null && it.clypeiform.isNotEmpty()) {
                            addClypeiformItem(it.clypeiform)
                        }
                    }
                }
            }
        }
        mUploadFileRequester.result.observe(this) { dataResult: DataResult<HttpBean<UploadFileApi.UploadBean>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.data.let {
                if (it != null) {
                    WaitDialog.show(getString(R.string.loading))
                    if (currentCameraType == CameraType.Front) {
                        currentPhotoUrl = it.anaemia
                        mCertificateRequester.request(
                            this,
                            it.anaemia,
                            "FRONT"
                        )
                    } else if (currentCameraType == CameraType.Back) {
                        currentPhotoUrl = it.anaemia
                        mCertificateRequester.request(
                            this,
                            it.anaemia,
                            "BACK"
                        )
                    }
                }
            }
        }

        //获取指定表单
        mAppointFormRequester.result.observe(this) { dataResult: DataResult<HttpBean<AppointFormApi.AbsquatulationBean>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.data.let {
                if (it != null && it.mothery != null && it.mothery.isNotEmpty()) {
                    val mothery = it.mothery[0]
                    mTerephthalate = mothery.terephthalate
                    mState.formType.set(mothery.terephthalate)
                    mState.title.set(mothery.arithmetical)
                    if (mothery.terephthalate == Const.SEPTA || mothery.terephthalate == Const.PDS) {
                        if (mothery.pippin == Const.MOONFLIGHT) {
                            render.addIdCard(
                                getString(R.string.click_to_upload_the_face_of_the_portrait),
                                "landmass",
                                ""
                            ).apply {
                                idCardListener = object : OnIdCardListener {
                                    override fun onImageView(
                                        imageViewFront: AppCompatImageView,
                                        imageViewBack: AppCompatImageView,
                                        stateView: AppCompatImageView,
                                        tipView: AppCompatTextView
                                    ) {
                                        mState.idCardFrontImageView = imageViewFront
                                        mState.idCardFrontStateView = stateView
                                        mState.idCardFrontTipView = tipView

                                        // 失败 bại
                                        // 成功 Thành công
                                        if (!tipView.text.toString()
                                                .contains(getString(R.string.success)) && !tipView.text.toString()
                                                .contains(getString(R.string.failure))
                                        ) {
                                            setSpannable(
                                                getString(R.string.click_to_upload),
                                                getString(
                                                    R.string.human_face
                                                ), tipView
                                            )
                                        }
                                    }
                                }
                            }.addListener =
                                object : OnIdAddListener {
                                    override fun onAdd() {
                                        idCardFront()
                                    }
                                }
                            render.addIdCard(
                                getString(R.string.click_to_upload_the_chip_side),
                                "dimerize",
                                ""
                            ).apply {
                                idCardListener = object : OnIdCardListener {
                                    override fun onImageView(
                                        imageViewFront: AppCompatImageView,
                                        imageViewBack: AppCompatImageView,
                                        stateView: AppCompatImageView,
                                        tipView: AppCompatTextView
                                    ) {
                                        mState.idCardBackImageView = imageViewBack
                                        mState.idCardBackStateView = stateView
                                        setSpannable(
                                            getString(R.string.click_to_upload),
                                            getString(R.string.chip_surface),
                                            tipView
                                        )
                                        mState.idCardBackTipView = tipView
                                    }
                                }
                            }.addListener =
                                object : OnIdAddListener {
                                    override fun onAdd() {
                                        idCardBack()
                                    }
                                }
                        }

                        return@observe
                    }
                    mothery.thorough.forEach { parentsItem ->
                        if (parentsItem.tabasco == Const.OLGA) {
                            var defValue = ""
                            val data = mutableListOf<FormSelectItem>().apply {
                                if (!parentsItem.mopishly.isNullOrEmpty()) {
                                    parentsItem.mopishly.forEach { item ->
                                        if (!formMap.isNullOrEmpty()) {
                                            val formKey = formMap[parentsItem.beastly]
                                            if (item.beastly == formKey.toString()
                                                    .split(Const.CONNECTOR)[0]
                                            ) {
                                                defValue = item.beastly
                                            }
                                        }
                                        val selectItem =
                                            FormSelectItem(item.giglot, item.beastly, order = -1)
                                        this.add(selectItem)
                                    }
                                }
                            }
                            render.addSelect(
                                SimpleDataProvider(data),
                                parentsItem.giglot,
                                parentsItem.beastly,
                                defValue,
                                dialogTitle = getString(R.string.choose) + parentsItem.giglot,
                                required = parentsItem.whakapapa
                            )
                        } else if (parentsItem.tabasco == Const.ARRIDE) {
                            var defValue = ""
                            val data = mutableListOf<FormSelectItem>().apply {
                                if (AppConfig.mAddress.isNotEmpty()) {
                                    AppConfig.mAddress.forEachIndexed { index, item ->
                                        if (!formMap.isNullOrEmpty()) {
                                            val formKey = formMap[parentsItem.beastly].toString()
                                                .split(Const.CONNECTOR)[0]
                                            if (item.beastly == formKey) {
                                                defValue = item.beastly
                                            }
                                        }
                                        val selectItem = FormSelectItem(
                                            item.giglot,
                                            item.beastly,
                                            order = -1,
                                            isNext = item.isAmelia
                                        )
                                        this.add(selectItem)
                                    }
                                }
                            }


                            val mAddressSelect = render.addSelect(
                                SimpleDataProvider(data),
                                parentsItem.giglot,
                                parentsItem.beastly,
                                defValue,
                                dialogTitle = getString(R.string.please_choose),
                                required = parentsItem.whakapapa
                            ).apply {
                                if (formMap.isNullOrEmpty()) return@apply

                                val formKeyStr =
                                    formMap[parentsItem.beastly]?.toString() ?: return@apply
                                if (formKeyStr.isEmpty()) return@apply

                                val formKeys = formKeyStr.split(Const.CONNECTOR)
                                if (formKeys.isEmpty()) return@apply

                                val key1 = formKeys.getOrNull(0) ?: return@apply
                                val item = provider.getItem(key1) ?: return@apply

                                onItemClick(
                                    item,
                                    provider,
                                    object : SelectFormItem.OnSelectedParameter {
                                        override fun onSelectedParameter(message: String) {
                                            if (formKeys.size <= 1) return

                                            val key2 = formKeys.getOrNull(1) ?: return
                                            val combinedItem =
                                                provider.getItem("$key1${Const.CONNECTOR}$key2")
                                                    ?: return

                                            onItemClick(
                                                combinedItem,
                                                provider,
                                                object : SelectFormItem.OnSelectedParameter {
                                                    override fun onSelectedParameter(message: String) {
                                                        setValueChanged(formKeyStr)
                                                    }
                                                })
                                        }
                                    })

                            }
                            mAddressProvider = mAddressSelect.provider
                            mAddressSelect.selectedListener = object : OnSelectedListener {
                                override fun onSelected(
                                    item: FormSelectItem,
                                    parameter: SelectFormItem.OnSelectedParameter
                                ) {
                                    onItemClick(item, mAddressProvider, parameter)
                                }
                            }


                        } else if (parentsItem.tabasco == Const.NARGHILE) {
                            val data = mutableListOf<FormSelectItem>().apply {
                                if (AppConfig.mJobs.isNotEmpty()) {
                                    AppConfig.mJobs.forEach { item ->
                                        val selectItem =
                                            FormSelectItem(item.giglot, item.beastly, order = -1)
                                        this.add(selectItem)
                                        item.unsellable.forEachIndexed { index, item ->
                                            if (selectItem.value != item.beastly) {
                                                selectItem.addChild(
                                                    FormSelectItem(
                                                        item.giglot,
                                                        item.beastly,
                                                        order = -1
                                                    )
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                            render.addSelect(
                                SimpleDataProvider(data),
                                parentsItem.giglot,
                                parentsItem.beastly,
                                null,
                                dialogTitle = getString(R.string.please_choose),
                                required = parentsItem.whakapapa
                            )
                        } else if (parentsItem.tabasco == Const.SYMPHYSIS) {
                            var formKey = ""
                            if (!formMap.isNullOrEmpty()) {
                                formKey = formMap[parentsItem.beastly].toString()
                                if (formKey != null && formKey.toString() == "null") {
                                    formKey = ""
                                }
                            }
                            render.addEditText(
                                parentsItem.giglot,
                                parentsItem.beastly,
                                formKey.toString(),
                                required = parentsItem.whakapapa
                            )
                        } else if (parentsItem.tabasco == Const.FAUCIAL) {
                            var formKey = ""
                            if (!formMap.isNullOrEmpty()) {
                                formKey = formMap[parentsItem.beastly].toString()
                                if (formKey != null && formKey.toString() == "null") {
                                    formKey = ""
                                }
                            }
                            render.addNumberEditText(
                                parentsItem.giglot,
                                parentsItem.beastly,
                                formKey.toString(),
                                required = parentsItem.whakapapa
                            ).apply {
                                this.filter = object : FormValueFilter {
                                    override fun filter(item: FormItem, value: String?): String? {
                                        if (parentsItem.giglot.toString()
                                                .contains(Const.ID_CARD_STR)
                                        ) {
                                            if (value == "-" || value == " " || value == "+") {
                                                return null
                                            }
                                        }
                                        return value
                                    }
                                }
                            }
                        } else if (parentsItem.tabasco == Const.MATZOTH) {
                            val prefix = parentsItem.beastly.toString()
                            val indexes = mutableSetOf<Int>()

                            formMap?.keys
                                ?.filterIsInstance<String>()
                                ?.forEach { key ->
                                    if (key.startsWith("$prefix.")) {
                                        key.split("_")
                                            .lastOrNull()
                                            ?.toIntOrNull()
                                            ?.let { indexes.add(it) }
                                    }
                                }
                            if (indexes.isEmpty() && formMap.isNullOrEmpty()) {
                                indexes.addAll(listOf(1, 2))
                            }
                            indexes.sorted().forEach { index ->
                                addContact(parentsItem, index, formMap, indexes)
                                addContactIndex = index
                            }
                        }
                    }
                }
            }
        }
        WaitDialog.show(getString(R.string.loading))
        mFormRequester.request(this, Const.THEOLOGIST)
    }

    private fun addBirthdayItem(value: String) {
        render.addDate(getString(R.string.date_of_birth), "sicative", value, required = true)
    }

    private fun addClypeiformItem(value: String) {
        render.addDate(getString(R.string.card_cccd), "clypeiform", value, required = true)
    }

    private fun addRapturousItem(value: String) {
        render.addDate(getString(R.string.have_a_time_limit), "rapturous", value, required = true)
    }

    private fun addOcrItem(bean: CertificateApi.ResCertificateBean, isCache: Boolean) {
        render.addEditText(
            getString(R.string.name),
            "attitudinize",
            bean.attitudinize,
            required = true
        )
        if (bean.sicative != null && bean.sicative.isNotEmpty()) {
            addBirthdayItem(bean.sicative)
        } else if (!isCache) {
            addBirthdayItem("")
        }
        var fattish = bean.fattish == "MALE"
        render.addRadioGroup(getString(R.string.gender), "fattish", fattish.toString(), false)
            .apply {
                this.setCheckBoxLabel(getString(R.string.male), getString(R.string.female))
            }
        render.addEditText(
            getString(R.string.Id_card_cccd_number),
            "reflexive",
            bean.reflexive,
            required = true
        ).tipListener = object : OnTipListener {
            override fun onTip() {
                XPopup.Builder(this@FormActivity)
                    .popupAnimation(PopupAnimation.TranslateFromBottom)
                    .asCustom(IdCardXpop(this@FormActivity))
                    .show()
            }
        }
        if (bean.rapturous != null && bean.rapturous.isNotEmpty()) {
            addRapturousItem(bean.rapturous)
        } else if (!isCache) {
            addRapturousItem("")
        }
    }


    private var addContactIndex = 1

    //添加联系人
    private fun addContact(
        parentsItem: MotheryBean.ThoroughBean,
        index: Int,
        formMap: HashMap<*, *>?,
        indexes: MutableSet<Int>
    ) {
        addContactIndex = index
        render.addGroupTitle(getString(R.string.emergency_contact_person) + index)
        var defValue = ""
        val data = mutableListOf<FormSelectItem>().apply {
            if (parentsItem.keel.liminal.isNotEmpty()) {
                parentsItem.keel.liminal.forEachIndexed { index, item ->
                    if (!formMap.isNullOrEmpty()) {
                        val formKey =
                            formMap[parentsItem.beastly + ".physiographer_$addContactIndex"]
                        if (item.beastly == formKey.toString()) {
                            defValue = item.beastly
                        }
                    }

                    val selectItem =
                        FormSelectItem(
                            item.giglot,
                            item.beastly,
                            order = -1
                        )
                    this.add(selectItem)
                }
            }
        }
        render.addSelect(
            SimpleDataProvider(data),
            getString(R.string.relationship),
            parentsItem.beastly + ".physiographer_$index",
            defValue,
            dialogTitle = getString(R.string.please_choose), required = parentsItem.whakapapa
        )
        val phoneKey = parentsItem.beastly + ".unparallel_$index"
        var formKey = ""
        if (!formMap.isNullOrEmpty()) {
            formKey = formMap[phoneKey].toString()
            if (formKey != null && formKey.toString() == "null") {
                formKey = ""
            }
        }

        render.addNumberEditText(
            getString(R.string.mobile_phone_number),
            phoneKey,
            formKey.toString(),
            required = parentsItem.whakapapa
        ).apply {
            this.filter = object : FormValueFilter {
                override fun filter(item: FormItem, value: String?): String? {
                    if (value == "-" || value == " ") {
                        return null
                    }
                    return value
                }
            }
            contactListener =
                object : OnContactSelectedListener {
                    override fun onContactSelected(editText: FormEditText) {
                        val intent = Intent(Intent.ACTION_PICK).apply {
                            type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
                        }
                        mState.editTextPhone = editText
                        mState.editTextPhone?.tag = phoneKey
                        contactLauncher.launch(intent)
                    }
                }
        }
        var nameKey = parentsItem.beastly + ".giglot_$index"
        if (nameKey != null && nameKey.toString() == "null") {
            nameKey = ""
        }
        var formValue = ""
        if (!formMap.isNullOrEmpty()) {
            formValue = formMap[nameKey].toString()
            if (formValue != null && formValue.toString() == "null") {
                formValue = ""
            }
        }
        render.addEditText(
            getString(R.string.name),
            nameKey,
            formValue.toString(),
            required = parentsItem.whakapapa
        ).apply {
            this.filter = object : FormValueFilter {
                override fun filter(item: FormItem, value: String?): String? {
                    if (value == " ") {
                        return null
                    }
                    return value
                }
            }
            contactListener =
                object : OnContactSelectedListener {
                    override fun onContactSelected(editText: FormEditText) {
                        mNameHasMap.put(phoneKey, editText)
                    }
                }
        }
        if (index >= indexes.size && index < 5) {
            val itemName = "addContact_$index"
            render.addButton(getString(R.string.add_an_emergency_contact), itemName, "")
                .addListener =
                object : OnAddListener {
                    override fun onAdd() {
                        formGroup.removeItem(itemName)
                        addContact(parentsItem, addContactIndex + 1, formMap, indexes)
                    }
                }
        }
    }

    private fun onItemClick(
        item: FormSelectItem,
        provider: FormDataProvider,
        parameter: SelectFormItem.OnSelectedParameter?
    ) {
        if (item.isNext) {
            WaitDialog.show(getString(R.string.loading))
            val apiValue = item.value.split(Const.CONNECTOR)
            DataRepository.getInstance().getAddress(
                this,
                GetAddressApi(apiValue.last())
            ) { result: DataResult<HttpBean<ArrayList<GetAddressApi.AddressBean>>> ->
                WaitDialog.dismiss()
                if (!result.responseStatus.isSuccess) {
                    ToastUtils.showShortToast(result.responseStatus.responseCode)
                    return@getAddress
                }
                val data = mutableListOf<FormSelectItem>().apply {
                    result.result.data?.let {
                        it.forEachIndexed { index, data ->
                            val selectItem =
                                FormSelectItem(
                                    data.giglot,
                                    item.value + Const.CONNECTOR + data.beastly,
                                    order = -1,
                                    isNext = data.isAmelia
                                )
                            item.addChild(selectItem)
                            this.add(item)
                        }

                    }
                }

                provider.addData(data)
                parameter?.onSelectedParameter("加载好了")
            }
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.activity_form, BR.vm, mState).addBindingParam(
            BR.click,
            Click()
        ).addBindingParam(BR.titleBarListener, TitleBarListener())

    }

    override fun onBackPressed() {
        if (shouldInterceptBack()) {
            // 执行拦截逻辑
            showExitConfirmDialog()
        } else {
            super.onBackPressed()
        }
    }

    private fun shouldInterceptBack(): Boolean {
        return true
    }

    override fun onStop() {
        super.onStop()
        mMessenger.input(Messages(Messages.EVENT_REFRESH_HOME))
        var formGroup = mAdapter.formGroup
        var formMap = formGroup.toMap()


        AppConfig.mConfigs.form().set(GsonUtils.toJson(formMap))
    }

    // 显示退出确认弹窗
    private fun showExitConfirmDialog() {
        CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.layout_form_back_tip) {
            override fun onBind(dialog: CustomDialog?, v: View?) {
                var tvContinue = v?.findViewById<TextView?>(R.id.tv_form_back_continue)
                var tvLeave = v?.findViewById<TextView?>(R.id.tv_form_back_leave)
                tvContinue?.setOnClickListener {
                    dialog?.dismiss()
                }
                tvLeave?.setOnClickListener {
                    dialog?.dismiss()
                    finish()
                }

            }
        }).setMaskColor(getColor(R.color.black30)).setAlign(CustomDialog.ALIGN.CENTER).setAnimResId(
            com.kongzue.dialogx.R.anim.anim_dialogx_alpha_enter,
            com.kongzue.dialogx.R.anim.anim_dialogx_default_exit
        )
    }


    inner class TitleBarListener : OnTitleBarListener {
        override fun onLeftClick(titleBar: TitleBar?) {
            super.onLeftClick(titleBar)
            showExitConfirmDialog()
        }

        override fun onRightClick(titleBar: TitleBar?) {
            super.onRightClick(titleBar)
        }
    }


    class FormStates : StateHolder() {

        val title: State<String> = State("")
        val formType: State<String> = State("")
        val formCount: State<Int> = State(0)
        val uploadSuccessBack: State<Boolean> = State(false)
        val uploadSuccessFront: State<Boolean> = State(false)
        val uploadFrontRes: State<Boolean> = State(true)
        val uploadBackRes: State<Boolean> = State(true)
        val landmass: State<String> = State("")
        val dimerize: State<String> = State("")
        val startLive: State<Boolean> = State(false)
        var editTextPhone: EditText? = null
        var isNext = false
        var idCardFrontImageView: AppCompatImageView? = null
        var idCardFrontStateView: AppCompatImageView? = null
        var idCardFrontTipView: AppCompatTextView? = null
        var idCardBackImageView: AppCompatImageView? = null
        var idCardBackStateView: AppCompatImageView? = null
        var idCardBackTipView: AppCompatTextView? = null

    }

    private fun uploadFile(file: String?) {
        MainHandler.postDelay(100) { WaitDialog.show(getString(R.string.loading)) }
        currentPhotoFile = File(file.toString())
        mUploadFileRequester.request(this@FormActivity, currentPhotoFile)
    }

    private val startForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            when (result.resultCode) {
                RESULT_OK -> {
                    val data: Intent? = result.data
                    val photoFile = data?.getStringExtra("photoFile")
                    uploadFile(photoFile)
                }

                RESULT_CANCELED -> {
                }
            }
        }

    private fun openCamera(type: CameraType) {
        currentCameraType = type
        val intent = Intent(this, OcrActivity::class.java)
        startForResult.launch(intent)
    }

    private val pickMedia =
        registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            uri?.let {
                val photoFile = Utils.getFileFromUri(this, uri)
                uploadFile(photoFile.toString())
            }
        }

    private fun openAlbum(type: CameraType) {
        currentCameraType = type
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    fun takePhotoDialog(mType: CameraType) {
        CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.xpop_photo) {
            override fun onBind(dialog: CustomDialog?, v: View?) {
                var clTakePic = v?.findViewById<ConstraintLayout?>(R.id.cl_take_pic)
                var clExample = v?.findViewById<ConstraintLayout?>(R.id.cl_example)
                if (mType == CameraType.Unknown) {
                    clTakePic!!.visibility = GONE
                    clExample!!.visibility = VISIBLE
                } else {
                    clTakePic!!.visibility = VISIBLE
                    clExample!!.visibility = GONE
                }
                var tvTakePhoto = v?.findViewById<TextView?>(R.id.tv_take_photo)
                var tvPhotoAlbum = v?.findViewById<TextView?>(R.id.tv_photo_album)
                var tvCancel = v?.findViewById<AppCompatTextView?>(R.id.tv_cancel)
                tvCancel?.setOnClickListener { dialog?.dismiss() }
                tvPhotoAlbum?.setOnClickListener(object : OnClickListener {
                    override fun onClick(view: View?) {
                        dialog?.dismiss()
                        this@FormActivity.openAlbum(mType)
                    }
                })

                tvTakePhoto?.setOnClickListener(OnClickListener { view: View? ->
                    dialog?.dismiss()
                    this@FormActivity.openCamera(mType)
                })

            }
        }).setMaskColor(getColor(R.color.black30)).setAlign(CustomDialog.ALIGN.BOTTOM).setAnimResId(
            com.kongzue.dialogx.R.anim.anim_dialogx_bottom_enter,
            com.kongzue.dialogx.R.anim.anim_dialogx_bottom_exit
        )
    }

    fun idCardFront() {
        if (!Utils.checkDebounce()) return
        takePhotoDialog(CameraType.Front)
    }

    fun idCardBack() {
        if (!Utils.checkDebounce()) return
        takePhotoDialog(CameraType.Back)
    }

    inner class Click {
        fun takPicDemo() {
            takePhotoDialog(CameraType.Unknown)
        }

        fun validate() {
            if (mTerephthalate == Const.PDS) {
                mState.startLive.set(true)
                this@FormActivity.startActivity(
                    Intent(
                        this@FormActivity,
                        LiveActivity::class.java
                    )
                )
//                this@FormActivity.finish()
                return
            }
            if (mTerephthalate == Const.SEPTA) {
                if (mState.landmass.get().isNullOrBlank()) {
                    TipDialog.show(getString(R.string.upload_photo_front_card))
                    return
                }
                if (mState.dimerize.get().isNullOrBlank()) {
                    TipDialog.show(getString(R.string.Please_upload_photo_back_card))
                    return
                }
                var map = formGroup.toMap()
                val result = formGroup.validateForm()
                if (!result.successfully()) {
                    TipDialog.show(result.message)
                    return
                }
                var pop = UserInfoXpop(
                    this@FormActivity,
                    map["attitudinize"],
                    map["reflexive"]
                )
                pop.setOnAgreeClickListener {

                    val nizamMap = HashMap<String?, Any?>()
                    for ((key, value) in map) {
                        nizamMap.put(key, value)
                    }
                    var bean = UploadUserInfoApi.ReqUploadUserInfoBean()
                    bean.setReflexive(map["reflexive"])
                    if (map["fattish"].toString() == true.toString()) {
                        bean.setFattish("MALE")
                    } else {
                        bean.setFattish("FEMALE")
                    }
                    bean.setAttitudinize(map["attitudinize"])
                    bean.setLandmass(mState.landmass.get())
                    bean.setDimerize(mState.dimerize.get())
                    bean.setSicative(map["sicative"])
                    bean.setClypeiform(map["clypeiform"])
                    bean.setRapturous(map["rapturous"])
                    WaitDialog.show(getString(R.string.loading))
                    mUploadUserInfoRequester.request(this@FormActivity, bean)
                }
                XPopup.Builder(this@FormActivity)
                    .popupAnimation(PopupAnimation.TranslateFromBottom)
                    .asCustom(pop)
                    .show()
                return
            }
            var formGroup = mAdapter.formGroup
            var map = formGroup.toMap()
            val result = formGroup.validateForm()
            if (!result.successfully()) {
                TipDialog.show(result.message)
                return
            }
            // 显式定义map类型为可变的嵌套结构
            val nizamMap = mutableMapOf<String, Any>()
            fun putKey(key: String, value: Any) {
                val keys = key.split(".")
                when {
                    keys.any { it.isEmpty() } -> throw IllegalArgumentException("Invalid key format: $key")
                    keys.size == 1 ->
                        nizamMap.put(keys[0], value)

                    else -> {
                        var currentMap: MutableMap<String, Any> = nizamMap
                        keys.dropLast(1).forEach { part ->
                            currentMap = (currentMap[part] as? MutableMap<String, Any>)
                                ?: mutableMapOf<String, Any>().also { currentMap[part] = it }
                        }
                        if (value is String && keys.last() == Const.IWW) {
                            val values = value.split(Const.CONNECTOR)
                            if (values.size > 1) {
                                currentMap[keys.last()] = values[0]
                                currentMap[Const.CAUTIONARY] = values[1]
                            } else {
                                currentMap[keys.last()] = value
                            }
                        } else if (value is String && keys.last() == Const.HUFFISH) {
                            val values = value.split(Const.CONNECTOR)
                            val huffishMap = mutableMapOf<String, Any>().apply {
                                values.getOrNull(0)?.takeIf { it.isNotEmpty() }
                                    ?.let { put(Const.BNDD, it) }
                                values.getOrNull(1)?.takeIf { it.isNotEmpty() }
                                    ?.let { put(Const.ANTENNARY, it) }
                                values.getOrNull(2)?.takeIf { it.isNotEmpty() }
                                    ?.let { put(Const.AMIDSHIP, it) }
                            }
                            currentMap[keys.last()] = huffishMap.takeIf {
                                it.size >= Const.MIN_HUFFISH_COMPONENTS
                            } ?: value
                        } else {
                            currentMap[keys.last()] = value
                        }
                    }
                }
            }

            val contactCache = mutableMapOf<String, MutableList<HashMap<String, Any>>>()
            for ((key, value) in map) {
                if (mTerephthalate == Const.INDWELL) {
                    val keys = key.split(".")
                    if (keys.size > 1 && keys[1].isNotBlank()) {
                        try {
                            val suffixNumber = keys[1].last().digitToInt()
                            val parentKey = keys[0] // 获取父级key作为缓存键
                            val contactMaps = contactCache.getOrPut(parentKey) {
                                MutableList(suffixNumber) { HashMap() }
                            }.also { list ->
                                while (list.size < suffixNumber) {
                                    list.add(HashMap())
                                }
                            }
                            contactMaps.last().put(keys[1].split("_")[0], value)
                            // 构建当前dataList（需要复制避免引用污染）
                            val dataList = contactMaps.map {
                                HashMap(it) // 深拷贝防止后续修改影响缓存
                            }.toMutableList()
                            nizamMap[parentKey] = dataList
                        } catch (e: NumberFormatException) {
                        }
                    }
                } else {
                    putKey(key, value)
                }
            }
            WaitDialog.show(getString(R.string.loading))
            mSubmitFormRequester.request(
                this@FormActivity, currentControl,
                nizamMap as java.util.HashMap<String?, in Any>?
            )
        }
    }
}